package com.elinkway.infinitemovies.ui.activity.commonwebview;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestVideoTask;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.OnePointRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.share.SharePopupWindow;
import com.elinkway.infinitemovies.ui.activity.BaseActionBarActivity;
import com.elinkway.infinitemovies.ui.activity.NewMainActivity;
import com.elinkway.infinitemovies.ui.activity.RankDetailActivity;
import com.elinkway.infinitemovies.ui.activity.TopicDetailActivity;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.utils.IdUtils;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.VideoEnabledWebView;
import com.le123.ysdq.R;

/**
 * 通用的WebView模块
 *
 * @author zhangshuo
 */
public class CommonWebViewActivity extends BaseActionBarActivity {

    public final static String TAG = "CommonWebViewActivity";

    private String mVideoTitle;

    private VideoEnabledWebView mWebView;

    private CommonWebViewClient mWebViewClient;

    private CommonWebViewManager mCommonManager;

    private String mFrom;

    private ImageView mShareImage;

    private PopupWindow mSharePopupWindow;

    private SharePopupWindow mShareWindow;

    private String mShareTitle = "分享内容";

    private String mSharePic = "http://www.coohua.com/share/invitation.html?ch=01yingshihuan";

    private String mShareDesc;

    private String loadUrl;

    private int icon;

    private boolean isNeedShare;
    private String fromTag;
    private long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        setContentView(R.layout.activity_common_webviewactivity);
        initActionBar();
        startTime=System.currentTimeMillis();
        mWebView = (VideoEnabledWebView) findViewById(R.id.commonwebview);

        mWebViewClient = new CommonWebViewClient(this) {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                LogUtils.e(CommonWebViewActivity.TAG, "shouldOverrideUrlLoading " + url + " " + uri.getQueryParameter(Utils.ACTION_TYPE)
                + uri.getScheme());
//                if (TextUtils.isEmpty(uri.getScheme()) || TextUtils.isEmpty(uri.getQueryParameter(Utils.ACTION_TYPE))
//                        || !IdUtils.SCHEME_NAME.equals(uri.getScheme())) {
//                    view.loadUrl(url);
//                    return true;
//                }
                if(url.startsWith("http")){
                    view.loadUrl(url);
                    return true;
                }else if(IdUtils.SCHEME_NAME.equals(uri.getScheme())){

                }else{
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MoviesApplication.getInstance().startActivity(intent);
                    }catch (Exception e){
                        //不支持scheme不做处理
                    }
                    return true;
                }
                LogUtils.e("", "Enter shouldOverrideUrlLoading " + uri.getQueryParameter("name"));
                if (Utils.TOPIC_DETAIL_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))) {
                    LogUtils.e("", "Enter TOPIC_DETAIL_ACTIVITY");
                    TopicDetailActivity.launch(CommonWebViewActivity.this, uri.getQueryParameter("themeId"), uri.getQueryParameter("name"));
                } else if (Utils.VIDEO_DETAIL_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))){
                    LogUtils.e("", "Enter VIDEO_DETAIL_ACTIVITY");
                    VideoDetailActivity.launch(CommonWebViewActivity.this, uri.getQueryParameter("videoId"),
                            uri.getQueryParameter("videoType"), uri.getQueryParameter("name"), "", uri.getQueryParameter("themeId"), "", "0","","");
                } else if (Utils.PLAY_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))) {
                    LogUtils.e("", "Enter PlayActivitySelfOwn");
                    RequestVideoTask requestVideoDataTask = new RequestVideoTask(CommonWebViewActivity.this, uri.getQueryParameter("videoId"),
                            uri.getQueryParameter("site"), uri.getQueryParameter("episodeNumber"), false);
                    requestVideoDataTask.start();
                } else if (Utils.RANK_DETAIL_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))) {
                    RankDetailActivity.launch(CommonWebViewActivity.this, uri.getQueryParameter("videoType"));
                } else if (Utils.WEB_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))) {
                    Utils.jumpWebViewActivity(CommonWebViewActivity.this, uri.getQueryParameter("url"),
                            uri.getQueryParameter("title"));
                } else if (Utils.MAIN_ACTIVITY.equals(uri.getQueryParameter(Utils.ACTION_TYPE))) {
                    LogUtils.e("", "Enter shouldOverrideUrlLoading MAIN");
                    Intent intent = null;
                    MoviesApplication.getInstance().setIsStartWebView(true);
                    intent = new Intent(CommonWebViewActivity.this, NewMainActivity.class);
                    startActivity(intent);
                }
                return true;
            }

        };
        initSharePopupWindow();
        mCommonManager = new CommonWebViewManager(this);
        getData();
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        mRightFirstIv.setImageResource(R.drawable.pic_share_normal);
        if (getIntent().getBooleanExtra("isNeedShare", false)) {
            mRightFirstIv.setVisibility(View.VISIBLE);
        } else {
            mRightFirstIv.setVisibility(View.GONE);
        }
        mRightFirstIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != mSharePopupWindow) {
                    mSharePopupWindow.showAtLocation(mRightFirstIv,
                            Gravity.CENTER, 0, 0);
                }
            }
        });
    }

    private void getData() {
        Intent intent = getIntent();
        isNeedShare = intent.getBooleanExtra("isNeedShare", false);
        if (null != intent) {
             if (null != intent.getSerializableExtra(Utils.CHANNEL_DTAT)) {
                 com.apkfuns.logutils.LogUtils.d("inner get channel dtat");
                 JumpData jumpData = (JumpData) intent.getSerializableExtra(Utils.CHANNEL_DTAT);
                 mFrom = intent.getStringExtra(Utils.FROM);
                 fromTag = intent.getStringExtra("fromTag");
                 mCommonManager.setFromPage(mFrom);
                 mVideoTitle = jumpData.getName();
                 mShareTitle = jumpData.getShareTitle();
                 mSharePic = jumpData.getSharePic();
                 mShareDesc = jumpData.getShareDesc();
                 loadUrl = jumpData.getPlayUrl();
                 icon = intent.getIntExtra("id", 0);
                 LogUtils.e(TAG, "!!!!!!!!!title!!!!!" + mVideoTitle);
                 LogUtils.e(TAG, "!!!!!!!!!loadUrl!!!!!" + loadUrl);
                 LogUtils.e(TAG, "shareDesc " + mShareDesc);
                 if (!TextUtils.isEmpty(mVideoTitle)) {
                     mTitleTv.setText(mVideoTitle);
                 } else {
                     mTitleTv.setText("");
                 }
             } else if (null != intent.getSerializableExtra(Utils.AD_INFO)) {
                 ServerPayload serverPayload = (ServerPayload) intent.getSerializableExtra(Utils.AD_INFO);
                 loadUrl = serverPayload.lp;
                 mFrom = intent.getStringExtra(Utils.FROM);
                 String appName = serverPayload.appName;
                 String packageName = serverPayload.packageName;
                 String adPos = intent.getStringExtra(Utils.AD_POS);
                 mCommonManager.setFromPage(mFrom);
                 mCommonManager.setAppName(appName);
                 mCommonManager.setPackageName(packageName);
                 mCommonManager.setAdPos(adPos);
                 com.apkfuns.logutils.LogUtils.d("inner get serverpayload:" + adPos);
             }
            if (!TextUtils.isEmpty(loadUrl) && null != mWebView) {
                setWebViewParameter(loadUrl);
            }
        }
    }

    private void initSharePopupWindow() {
        mShareWindow = new SharePopupWindow(this, 2);
        mSharePopupWindow = mShareWindow.initPopWindow();
    }

    private void setWebViewParameter(String url) {
        WebSettings websettings = mWebView.getSettings();

        String ua = websettings.getUserAgentString();
        mWebView.getSettings().setUserAgentString(ua+" LVideo/"+ MoviesHttpApi.PLATFORM_IN_UPGRADE);

        websettings.setJavaScriptCanOpenWindowsAutomatically(true);
        websettings.setUseWideViewPort(true);
        websettings.setLoadWithOverviewMode(true);
        websettings.setDomStorageEnabled(true);
        websettings.setRenderPriority(RenderPriority.HIGH);
        websettings.setJavaScriptEnabled(true);
        websettings.setPluginState(websettings.getPluginState().ON);
        websettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setWebChromeClient(new CommonWebChromclient(mTitleTv));
        mWebView.requestFocus();
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setDownloadListener(mCommonManager.getmDownLoadListener());
        LogUtils.e(TAG, "setWebViewParameter method called and adURL is " + url);
        mWebView.loadUrl(url);
//        mWebView.addJavascriptInterface(new JumpActivityJavaScriptInterface(), "JS");
    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            if (null != mWebView) {
                mWebView.getClass().getMethod("onPause")
                        .invoke(mWebView, (Object[]) null);
                mWebView.clearHistory();
                mWebView.removeAllViews();
                mWebView.destroy();
                mWebView = null;
            }

            if (null != mWebViewClient) {
                mWebViewClient.destory();
                mWebViewClient = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public VideoEnabledWebView getmWebView() {
        return mWebView;
    }

    public void setShareTitle(String title) {
        mShareTitle = title;
    }

    public String getShareTitle() {
        if (TextUtils.isEmpty(mShareTitle)) {
            return "";
        }
        return mShareTitle;
    }
    public String getVideoTitle() {
        if (TextUtils.isEmpty(mVideoTitle)) {
            return "";
        }
        return mVideoTitle;
    }


    public void setSharePic(String shareLink) {
        mSharePic = shareLink;
    }

    public String getSharePic() {
        if (TextUtils.isEmpty(mSharePic)) {
            return "";
        }
        return mSharePic;
    }

    public void setShareDesc(String shareDesc) {
        mShareDesc = shareDesc;
    }

    public String getShareDesc() {
        if (TextUtils.isEmpty(mShareDesc)) {
            return "";
        }
        return mShareDesc;
    }

    public String getLoadUrl() {
        if (TextUtils.isEmpty(loadUrl)) {
            return "";
        }
        return loadUrl;
    }

    @Override
    public void dealWithUmeng() {
    }

    @Override
    public void dealWithVisitUmeng() {

    }

    @Override
    protected void onPause() {
        if (!TextUtils.isEmpty(fromTag)&&"onePiontSource".equals(fromTag)){
            OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
            record.setCur_url("yidianweb");
            record.setResidenceTime(String.valueOf((System.currentTimeMillis() - startTime)/1000));
            RealmDaoManager.addMyDataRecord(record);
        }
        super.onPause();
    }


}
